﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace Collector
{
    public partial class LedFrm : Form
    {
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "DestroyWindow")]
        [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
        public static extern bool DestroyWindow(int hWnd);

        [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "SendMessageW")]
        static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);

        [System.Runtime.InteropServices.DllImport("avicap32.dll", EntryPoint = "capCreateCaptureWindowW")]
        static extern int capCreateCaptureWindow(string lpszWindowName, int dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, int nID);
        
        [DllImport("User32.dll", EntryPoint = "PostMessage")]
        public static extern int PostMessage(
            IntPtr hWnd,        // 信息发往的窗口的句柄
            int Msg,            // 消息ID
            int wParam,         // 参数1
            TestItemFlow lParam // 参数2
        );
        const int WM_CHK_PASS = 1001;
        const int WM_CHK_FAIL = 1002;

        public static IntPtr hWndParent;
        public static int hWndC = 0;
        public static int cameraLedState = 0;
        public static short WM_CAP = 1024;
        public static int WM_CAP_DRIVER_CONNECT = WM_CAP + 10;
        public static int WM_CAP_DRIVER_DISCONNECT = WM_CAP + 11;
        public static int WS_CHILD = 0x40000000;
        public static int WS_VISIBLE = 0x10000000;

        //X86BIOS.BaseBios mBios = null;
        //GlobalConfigure.GlobalConfigure mCfg = null;
        static AutoResetEvent LedTestWaitEvent = new AutoResetEvent(false);
        //eLedType mCurrentClickLetType = eLedType.NA;
        ComPortPack comPort_;

        /// <summary>
        /// 0 默认操作,1 等待PASS或FAIL操作,2 PASS按下 ,3 FAIL按下
        /// </summary>
        //int mState = 0;
        public bool TestState { get; set; }
        public int randomNumber { get; set; }
        TestItemFlow currentTestItem = TestItemFlow.NA;
        public LedFrm(/*BaseKeyBoard mBaseKB,*/ ComPortPack comPort, TestItemFlow TestItem)
        {
            InitializeComponent();
            this.TestState = false;
            comPort_ = comPort;
            //mBaseKB_ = mBaseKB;
            //currentCustomer_ = currentCustomer;
            currentTestItem = TestItem;
            this.Shown += LedFrm_Shown;
            this.FormClosing += LedFrm_FormClosing;
            this.KeyPress += LedFrm_KeyPress;
            //this.btnPass.Visible = true;
            hWndParent = this.Handle;
        }

        void LedFrm_FormClosing(object sender, FormClosingEventArgs e)
        {

        }
        private void LedFrm_Load(object sender, EventArgs e)
        {
            //Thread nth = new Thread(() =>
            //{
            //    for (int i = 0; i < 200; i++)
            //    {
            //        set_LED_ON();
            //        Thread.Sleep(500);
            //        if (TestState)
            //            break;
            //    }
            //});
            //nth.Start();
        }

        void LedFrm_Shown(object sender, EventArgs e)
        {
            ItemTest();
        }

        void ItemTest()
        {
            switch (currentTestItem)
            {
                case TestItemFlow.Led1Test:
                    LedTest_();
                    break;
                case TestItemFlow.SFTAirTest:
                    SFTAirTest_();
                    break;
                default:
                    break;
            }
        }


        void LedTest_()
        {
            this.ShowMsg(string.Format("请确认 Led 灯闪烁状态"), Color.Blue);
            this.btnPass.Focus();
            Thread nth = new Thread(() =>
            {
                set_LED_Flicker();//闪烁
            });
            nth.Start();
        }
        void SFTAirTest_()
        {
            this.ShowMsg(string.Format("请确认气囊充气状态"), Color.Blue);
            this.btnPass.Focus();
        }
        void LedTest()
        {
            bool bRetry = false;
            Thread _thread = new Thread(new ThreadStart(delegate
            {
                Random rd = new Random();
                var num = -1;
                //mBaseKB_.HidEnterTestMode();
                num = rd.Next(1, 4);
                for (int i = 0; i < num; i++)
                {
                    set_LED_ON();
                    Thread.Sleep(2000);
                    //set_LED_OFF();
                    //Thread.Sleep(1000);
                }
                this.ShowMsg("请选择对应的闪烁次数", Color.Blue);
                LedTestWaitEvent.WaitOne();
                LedTestWaitEvent.Reset();
                //this.ShowMsg("Waiting...", Color.Blue);
                if (num != randomNumber)
                {
                    this.ShowMsg("测试fail,请重新测试", Color.Red);
                    bRetry = true;
                }

                //mBaseKB_.HidExitTestMode();
                if(bRetry)
                {
                    this.Invoke(new EventHandler(delegate
                    {
                        this.btnPass.Visible = true;
                        this.btnPass.Enabled = true;
                        btnPass.Focus();
                    }));
                }
                else
                {
                    //set_LED_ON();
                    this.TestState = true;
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                    //this.Invoke(new EventHandler(delegate
                    //{
                    //    IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;
                    //    PostMessage(handle, WM_CHK_PASS, 0, currentTestItem);
                    //    this.TestState = true;
                    //    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    //    this.Close();
                    //}));
                    //this.TestState = true;
                    //this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }));
            _thread.Start();
        }

        /// <summary>
        /// 关闭LED，2020-6-24
        /// </summary>
        private void set_LED_OFF()
        {
            byte[] Cmdata1 = FileConfig.getSerialPortData("SPLedOFF");//0x55, 0x55, 0xaa, 0xaa, 0x02, 0x52, 0x04
            byte[] receiveData = new byte[Cmdata1.Length];
            comPort_.SendData(Cmdata1, 0, Cmdata1.Length);
            //comPort_.SendCommand(Cmdata1, ref receiveData, 5);
            Log.Debug("set_LED_OFF,receiveData :" + ConvertFuncs.ByteArrayToHexString(receiveData));
        }
        /// <summary>
        /// 开启LED，2020-6-24
        /// </summary>
        ///灯闪烁
        private void set_LED_ON()
        {
            byte[] Cmdata1 = FileConfig.getSerialPortData("SPLedON");//0x55, 0x55, 0xaa, 0xaa, 0x02, 0x52, 0x04
            byte[] receiveData = new byte[Cmdata1.Length];
            comPort_.SendData(Cmdata1, 0, Cmdata1.Length);
            //comPort_.SendCommand(Cmdata1, ref receiveData, 5);
            Log.Debug("set_LED_ON,receiveData :" + ConvertFuncs.ByteArrayToHexString(receiveData));
        }
        private void set_LED_Flicker()
        {
            byte[] Cmdata1 = FileConfig.getSerialPortData("SPLedFlicker");//0x55, 0x55, 0xaa, 0xaa, 0x02, 0x52, 0x04
            byte[] receiveData = new byte[Cmdata1.Length];
            comPort_.SendData(Cmdata1, 0, Cmdata1.Length);
            //comPort_.SendCommand(Cmdata1, ref receiveData, 5);
            Log.Debug("set_LED_Flicker,receiveData :" + ConvertFuncs.ByteArrayToHexString(receiveData));
        }
        private void ShowMsg(string msg, Color _clr)
        {
            this.lbMsg.Invoke(new EventHandler(delegate
            {
                this.lbMsg.ForeColor = _clr;
                this.lbMsg.Text = msg;
            }));
        }
        private void btnfail_Click(object sender, EventArgs e)
        {
            set_LED_ON();
            this.TestState = false;
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
            //this.Invoke(new EventHandler(delegate
            //{
            //    //IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;
            //    //PostMessage(handle, WM_CHK_FAIL, 0, currentTestItem);
            //    this.TestState = false;
            //    this.DialogResult = System.Windows.Forms.DialogResult.OK;
            //    this.Close();
            //}));
        }

        private void btnPass_Click(object sender, EventArgs e)
        {
            set_LED_ON();
            this.TestState = true;
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void btnretry_Click(object sender, EventArgs e)
        {
            ItemTest();
            //this.ShowMsg("waiting...", Color.Blue);
            //this.Invoke(new EventHandler(delegate
            //{
            //    this.btnretry.Visible = false;
            //    this.btnretry.Enabled = false;
            //}));
            //LedTest();

            //人工判断LED灯状态
            //set_LED_OFF();
            //this.TestState = true;
            //this.DialogResult = System.Windows.Forms.DialogResult.OK;
            //this.Close();
        }
        private void LedFrm_KeyPress(object sender, KeyPressEventArgs e)
        {
            Log.Debug("LedFrm_KeyPress e.KeyChar :" + e.KeyChar);
            if (e.KeyChar == '1')
            {
                btnnum1_Click(sender, e);
            }
            if (e.KeyChar == '2')
            {
                btnnum2_Click(sender, e);
            }
            if (e.KeyChar == '3')
            {
                btnnum3_Click(sender, e);
            }
        }
        private void btnnum1_Click(object sender, EventArgs e)
        {
            this.AddResult(1);
        }

        private void btnnum2_Click(object sender, EventArgs e)
        {
            this.AddResult(2);
        }

        private void btnnum3_Click(object sender, EventArgs e)
        {
            this.AddResult(3);
        }

        private void btnnum4_Click(object sender, EventArgs e)
        {
            this.AddResult(4);
        }

        private void btnnum0_Click(object sender, EventArgs e)
        {
            this.AddResult(0);
        }
        private void AddResult(int num)
        {
            randomNumber = num;
            LedTestWaitEvent.Set();
        }
    }

    public enum eLedType
    {
        NA,
        CHG_LOW_LED,
        CHG_LED,
        CHG_FULL_LED,
        CAPS_LOCK_LED,
        FN_LOCK_LED,
        PWR_LED,
        NUM_LOCK_LED,
        CAMERA_LED,
        KB_BACK_LED,
        HDD_LED,
        MIC_LED,
        FN_KEY,
        WL_KEY
    }
    //public class MyButton : Button
    //{
    //    //BASEEC mEc = null;
    //    BaseKeyBoard _mBaseKB_ = null;
    //    public MyButton(BaseKeyBoard mBaseKB)
    //    {
    //        _mBaseKB_ = mBaseKB;
    //        this.Size = new Size(133, 69);
    //        this.ImageAlign = ContentAlignment.TopCenter;
    //        this.TextAlign = ContentAlignment.BottomCenter;
    //        //this.ShowBtnLedStatus(false);
    //    }
    //    public eLedType LedType { get; set; }
    //    public bool CheckState { get; set; }

    //    public void ShowBtnLedStatus(bool IsOn)
    //    {
    //        switch (LedType)
    //        {
    //            case eLedType.CHG_LOW_LED:
    //                this.Image = IsOn ? global::KeyboardTest.Properties.Resources.power_led_on : global::KeyboardTest.Properties.Resources.power_led_off;
    //                break;
    //            case eLedType.CHG_LED:
    //                this.Image = IsOn ? global::KeyboardTest.Properties.Resources.power_led_on : global::KeyboardTest.Properties.Resources.power_led_off;
    //                break;
    //            case eLedType.CHG_FULL_LED:
    //                this.Image = IsOn ? global::KeyboardTest.Properties.Resources.power_led_on : global::KeyboardTest.Properties.Resources.power_led_off;
    //                break;
    //            case eLedType.CAPS_LOCK_LED:
    //                this.Image = IsOn ? global::KeyboardTest.Properties.Resources.power_led_on : global::KeyboardTest.Properties.Resources.power_led_off;
    //                break;
    //            case eLedType.FN_LOCK_LED:
    //                this.Image = IsOn ? global::KeyboardTest.Properties.Resources.power_led_on : global::KeyboardTest.Properties.Resources.power_led_off;
    //                break;
    //            case eLedType.PWR_LED:
    //                this.Image = IsOn ? global::KeyboardTest.Properties.Resources.power_led_on : global::KeyboardTest.Properties.Resources.power_led_off;
    //                break;
    //            case eLedType.KB_BACK_LED:
    //                this.Image = IsOn ? global::KeyboardTest.Properties.Resources.power_led_on : global::KeyboardTest.Properties.Resources.power_led_off;
    //                break;
    //            case eLedType.FN_KEY:
    //                this.Image = IsOn ? global::KeyboardTest.Properties.Resources.caps_lock_on : global::KeyboardTest.Properties.Resources.caps_lock_off;
    //                break;
    //            case eLedType.WL_KEY:
    //                this.Image = IsOn ? global::KeyboardTest.Properties.Resources.caps_lock_on : global::KeyboardTest.Properties.Resources.caps_lock_off;
    //                break;
    //            default:
    //                this.Image = global::KeyboardTest.Properties.Resources.power_led_off;
    //                break;
    //        }
    //    }

    //    public eLedType SetLedState(bool isOn)
    //    {
    //        switch (LedType)
    //        {
    //            case eLedType.CHG_LED:
    //                if (isOn)
    //                    _mBaseKB_.HidChargeOrangeLedON();
    //                else
    //                    _mBaseKB_.HidChargeOrangeLedOFF();
    //                break;
    //            case eLedType.CAPS_LOCK_LED:
    //                if (isOn)
    //                    _mBaseKB_.HidCapsLockLedON();
    //                else
    //                    _mBaseKB_.HidCapsLockLedOFF();
    //                break;
    //            case eLedType.FN_LOCK_LED:
    //                if (isOn)
    //                    _mBaseKB_.HidFnLockLedON();
    //                else
    //                    _mBaseKB_.HidFnLockLedOFF();
    //                break;
    //            case eLedType.PWR_LED:
    //                if (isOn)
    //                    _mBaseKB_.HidPowerLedON();
    //                else
    //                    _mBaseKB_.HidPowerLedOFF();
    //                break;
    //            case eLedType.KB_BACK_LED:
    //                if (isOn)
    //                    _mBaseKB_.HidBacklightLedON();
    //                else
    //                    _mBaseKB_.HidBacklightLedOFF();
    //                break;
    //            default:
    //                break;
    //        }
    //        return LedType;
    //    }
    //}
}